package com.example.jbmsuppliers.sinopec.doorjurisd;

import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.jbmsuppliers.R;
import com.example.jbmsuppliers.bluetooth.le.DoorEvent;
import com.example.jbmsuppliers.bluetooth.le.OpenCtrl;
import com.example.jbmsuppliers.sinopec.activity.MyMabageDoor;
import com.example.jbmsuppliers.sinopec.net.NetWork;
import com.example.jbmsuppliers.sinopec.net.busheven.UtlisNetWork;
import com.example.jbmsuppliers.sinopec.sqlist.MyOpenLog;
import com.example.jbmsuppliers.sinopec.sqlist.MySqliUtlis;
import com.example.jbmsuppliers.sinopec.utlis.OpenKey;
import com.example.jbmsuppliers.sinopec.utlis.SaveOpenKeyManage;
import com.example.jbmsuppliers.sinopec.view.DoubleButtonDialog;
import com.example.jbmsuppliers.sinopec.view.MyToast;
import com.jbm.jbmsupplier.util.IEGLog;
import com.jbm.jbmsupplier.util.IEGLogCtrl;
import com.jbm.jbmsupplier.util.IEGuardKey;
import com.jbm.jbmsupplier.util.IEGuardKeyCtrl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import static com.example.jbmsuppliers.sinopec.doorjurisd.SensorService.SERSONWINSOW;
import static com.jbm.jbmsupplier.util.abstracts.SendMessageInterfase.gSocket;

/**
 * Created by 家帮忙 on 2017/2/17.
 */

public class DoorOpenBlue {

    private static DoorOpenBlue doorOpenBlue;
    private  String vivler;
    private  ArrayList<IEGuardKey> arr;
    private ArrayList<IEGuardKey> ArrayListIEKey;
    private  SharedPreferences.Editor sharlog;
    private SharedPreferences sharedPreferences, sharedPreferenceslog;
    private BluetoothAdapter mBluetoothAdapter;
    private  float Volume;
    private Vibrator vibratorr;
    private Context con;
    private IEGuardKeyCtrl iekc;
    private IEGuardKey egkeys;
    private int is_open;
    private SoundPool sp;
    public final static int OPENKEY = 0000;
    private final int OPENSUCCESS = 0001;
    private final int OPENSERSON = 0002;
    private final int NOTFOUND = 0003;
    private final int SERSONOPENSUCCESS = 0004;
    private final int VOLUME = 0005;
    private Handler handlerpuball;
    private String tableopemerr = "";
    private TextView te;
   
    private TextView texts;
    private Timer ti;
    private ImageView images;
    private Dialog pre;

    public DoorOpenBlue() {
    }

    public  DoorOpenBlue(Context c, Handler handlerpuball) {
        this.con = c;
        this.handlerpuball = handlerpuball;
       ArrayListIEKey = new ArrayList<>();
        sharedPreferences = c.getSharedPreferences("open_key_judge", Activity.MODE_PRIVATE);//保存开门的时候用int类型来记录开门的时间
        sharedPreferenceslog = c.getSharedPreferences("open_door_log", Activity.MODE_PRIVATE);//保存蓝牙开门反馈给用户展示的信息
        sharlog= sharedPreferenceslog.edit();
        BluetoothManager bluetoothManager = (BluetoothManager) c.getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();
        AudioManager manager = (AudioManager) c.getSystemService(Context.AUDIO_SERVICE);
        int maxVolume = manager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        int currentVolume = manager.getStreamVolume(AudioManager.STREAM_MUSIC);
        Volume = currentVolume / (float) maxVolume;
        PackageManager packageManager=c.getPackageManager();
        try {
            PackageInfo vivle = packageManager.getPackageInfo(c.getPackageName(), 0);
           vivler= vivle.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
//setDialog();
    }





    public void OpenDoorGather(String name, TextView textView, final Context context, Activity activity, ImageView image) {
        this.te=textView;
        OpenCtrl ctrl = new OpenCtrl();
        arr = new SaveOpenKeyManage(con).setgainOpenKey();
        if (arr==null){
            hint("没有开门权限，请求分发或认证,+"+"\n"+"+请到我的页面手机开门设置认证");
            return;}
        if (arr.size() > 0) {
            iekc = new IEGuardKeyCtrl();
            iekc.EGKlist = new IEGuardKey[arr.size()];
            for(int i=0;i<arr.size();i++) {
                if (arr.get(i).open_count == 0) {
                    hint("没有开门权限，请求分发或认证,+" + "\n" + "+请到我的页面手机开门设置认证");
                    return;
                } else {
                    iekc.EGKlist[i] = arr.get(i);
                }
            }
            if (name.equals("FloatWindow")) {
                setViratoor();
                OpenKey.getinstant().setName("悬浮按钮开");
                OpenKey.getinstant().setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis())));
                sharedPreferences.edit().putInt("intopen", 1).commit();
                FuMbleOpenDoor(ctrl, context, activity, "FloatWindow",iekc);
                textView.setBackground(context.getResources().getDrawable(R.mipmap.kaisuo));
                sharlog.putString("info","开门中...").commit();
                    pre = new Dialog(con,R.style.dialogLoading);
                    pre.setContentView(R.layout.lz_laoutprogress);
                     images = (ImageView) pre.findViewById(R.id.clean_rotate);
                    texts = (TextView) pre.findViewById(R.id.te_door_kaimen);
                    pre.setCancelable(false);
                    Animation anim = AnimationUtils.loadAnimation(con, R.anim.rptate_repate);
                    anim.setInterpolator(new LinearInterpolator());
                    images.setAnimation(anim);
                    pre.show();

                if (ti==null){
                    ti=  new Timer();
                    ti.scheduleAtFixedRate(new RefreshTask(),0,500);
                }
            } else if (name.equals("SerSon")) {
                // 检查设备上是否支持蓝牙
                if (mBluetoothAdapter.isEnabled()) {
                    setViratoor();
                    OpenKey.getinstant().setName("摇一摇开");
                    OpenKey.getinstant().setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis())));
                    FuMbleOpenDoor(ctrl, context, activity, "SerSon",iekc);
                    sharedPreferences.edit().putInt("intopen", 1).commit();

                }
            }


        }else{
            hint("没有开门权限，请求分发或认证,+"+"\n"+"+请到我的页面手机开门设置认证");
        }


    }

String info;
    private void FuMbleOpenDoor(OpenCtrl ctrl, final Context context, Activity activity, final String sign,IEGuardKeyCtrl iekc) {
        ctrl.Open(1333, 3, iekc, context, activity, new DoorEvent() {
            @Override
            public void OpenSuccess(IEGuardKey egkey, String mac) {
                //开门成功
                SetCheckoutOpenCount(egkey);
                is_open = 1;
                tableopemerr = "开门成功";
                sharlog.putString("info",tableopemerr).commit();
                if (sign.equals("FloatWindow")) {
                    handler.sendMessage(handler.obtainMessage(OPENSUCCESS, "FloatWindow"));
                } else if (sign.equals("SerSon")) {
                    handler.sendMessage(handler.obtainMessage(SERSONOPENSUCCESS, "SerSon"));
                }
                getkaimen();
                MyToast.show(con,tableopemerr,0);
            }

            @Override
            public void OpenFailed(IEGuardKey egkey, String mac) {
                //开门失败
                egkeys = egkey;
                is_open = 0;
                tableopemerr = "开门失败";
                sharlog.putString("info",tableopemerr).commit();
                if (sign.equals("FloatWindow")) {
                    handler.sendMessage(handler.obtainMessage(NOTFOUND, "FloatWindow"));
                } else if (sign.equals("SerSon")) {
                    handler.sendMessage(handler.obtainMessage(OPENSERSON, "SerSon"));
                }
                getkaimen();

            }

            @Override
            public void NotFound() {
                //未找到蓝牙设备
                is_open = 0;
                tableopemerr = "未找到蓝牙设备";
                sharlog.putString("info",tableopemerr).commit();

                if (sign.equals("FloatWindow")) {
                    handler.sendMessage(handler.obtainMessage(NOTFOUND, "FloatWindow"));
                } else if (sign.equals("SerSon")) {
                    handler.sendMessage(handler.obtainMessage(OPENSERSON, "SerSon"));
                }
                getkaimen();
            }

            @Override
            public void OtherError(String errorinfo) {
                //所有关于蓝牙的相关报错信息
                is_open = 0;
                tableopemerr = errorinfo;
                sharlog.putString("info",tableopemerr).commit();
                if (sign.equals("FloatWindow")) {
                    handler.sendMessage(handler.obtainMessage(NOTFOUND, "FloatWindow"));
                } else if (sign.equals("SerSon")) {
                    handler.sendMessage(handler.obtainMessage(OPENSERSON, "SerSon"));
                }
                getkaimen();
            }

            @Override
            public void OpenStatus(String info) {
                //再有们的情况下开门给用户的提示数据
                tableopemerr=info;
                sharlog.putString("info",tableopemerr).commit();
            }
        }, false);

    }


    private void setViratoor() {
        vibratorr = (Vibrator) con.getSystemService(Context.VIBRATOR_SERVICE);
        long[] pattern = {100, 400, 100, 400}; // 停止 开启 停止 开启
        vibratorr.vibrate(pattern, -1);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                vibratorr.cancel();
            }
        }, 500);

    }


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case OPENKEY: {
                    String upload = (String) msg.obj;
                    if (upload.equals("OK")) {
                        MySqliUtlis.getInstance(con).DeleteOp();//开门成功后删除日志表的所有数据
                        Log.e("main", "成功" + upload);
                    } else if (upload.equals("time out")) {
                    } else {
                        return;
                    }
                    break;
                }
                case VOLUME: {
                    sp = new SoundPool(1, AudioManager.STREAM_SYSTEM, 0);//第一个参数为同时播放数据流的最大个数，第二数据流类型，第三为声音质量
                     sp.load(con, R.raw.dingdong, 1);
                    sp.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
                        @Override
                        public void onLoadComplete(SoundPool soundPool, int i, int i1) {
                            soundPool.play(i, Volume, Volume, 1, 0, 1);
                        }
                    });
//                    sp.play(s, 1, 1, 1, 0, 1f);

                    break;
                }
                case OPENSUCCESS: {
                            handler.sendEmptyMessageDelayed(VOLUME, 70);
                    if (pre!=null){
                        pre.dismiss();
                    }
                    setEccss();
                    break;
                }
                case SERSONOPENSUCCESS: {
                            handler.sendEmptyMessageDelayed(VOLUME, 70);
                            handlerpuball.sendEmptyMessageDelayed(SERSONWINSOW, 8000);
                    break;
                }
                case NOTFOUND: {
                    if (pre!=null){
                        pre.dismiss();
                    }
                    setError();
                    break;
                }
                case OPENSERSON: {
                            handlerpuball.sendEmptyMessageDelayed(SERSONWINSOW, 8000);

                    break;
                }

            }
        }
    };
//悬浮按钮开门成功
    public void setEccss(){
        te.setBackground(con.getResources().getDrawable(R.mipmap.kaisuo_hui));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if(ti!=null){
                    ti.cancel();
                    ti=null;}
                te.setBackground(con.getResources().getDrawable(R.mipmap.kaisuo_moren));
                con.getSharedPreferences("open_key_judge", Activity.MODE_PRIVATE).edit().clear().commit();

            }
        },8000);


    }
    //悬浮按钮开门失败
    public void setError(){

        te.setBackground(con.getResources().getDrawable(R.mipmap.lz_kaimenshibai));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                te.setBackground(con.getResources().getDrawable(R.mipmap.kaisuo_moren));
                con.getSharedPreferences("open_key_judge", Activity.MODE_PRIVATE).edit().clear().commit();
            }
        },10000);


    }









    private void SetCheckoutOpenCount(IEGuardKey egkey){
        for(int i=0;i<arr.size();i++){
            if (arr.get(i).open_key.equals(egkey.open_key)){
                if (egkey.open_total!=-1){
                    int count= arr.get(i).open_count-1;
                    egkey.open_count=count;
                    egkeys=egkey;
                }else{

                }
            }
        }
        if (egkey.open_total==-1){
            egkeys=egkey;
        }
        ArrayListIEKey.add(egkeys);
        new SaveOpenKeyManage(con).setsaveOpenkey(ArrayListIEKey);
    }
    public void getkaimen() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());
        String date = formatter.format(curDate);
        try {
            if (tableopemerr.equals("")) {
                return;
            }
            if (egkeys == null) {
                MySqliUtlis.getInstance(con).Opendatakey(gSocket.login_id, 0, 0, 0, date, date, is_open, 0, Build.MODEL + Build.VERSION.RELEASE, OpenKey.getinstant().getName(), OpenKey.getinstant().getTime(), date, tableopemerr+vivler);
            } else {
                MySqliUtlis.getInstance(con).Opendatakey(egkeys.login_id, egkeys.eguard_id, egkeys.egkey_id, egkeys.open_count, date, date, is_open, 0, Build.MODEL + Build.VERSION.RELEASE, OpenKey.getinstant().getName(), OpenKey.getinstant().getTime(), date, tableopemerr+vivler);
            }
            ArrayList<MyOpenLog> listopen = MySqliUtlis.getInstance(con).ShowddataOpenKey();
            IEGLogCtrl ieglog = new IEGLogCtrl();
            ieglog.EGLlist = new IEGLog[listopen.size()];
            for (int i = 0; i < listopen.size(); i++) {
                ieglog.EGLlist[i] = new IEGLog();
                ieglog.EGLlist[i].login_id = listopen.get(i).getLogin_id();
                ieglog.EGLlist[i].eguard_id = listopen.get(i).getEguard_id();
                ieglog.EGLlist[i].egkey_id = listopen.get(i).getEgkey_id();
                ieglog.EGLlist[i].last_count = listopen.get(i).getLast_count();
                ieglog.EGLlist[i].open_date = listopen.get(i).getOpen_date();
                ieglog.EGLlist[i].create_date = listopen.get(i).getCreate_date();
                ieglog.EGLlist[i].is_open = listopen.get(i).getIs_open();
                ieglog.EGLlist[i].try_cnt = listopen.get(i).getTry_cnt();//重复开门次数
                ieglog.EGLlist[i].phone_module = listopen.get(i).getPhone_module();
                ieglog.EGLlist[i].open_type = listopen.get(i).getOpen_type();
                ieglog.EGLlist[i].ord_date = listopen.get(i).getOrd_date();
                ieglog.EGLlist[i].call_date = listopen.get(i).getCall_date();
                ieglog.EGLlist[i].errinfo = listopen.get(i).getError();
            }
           int mode= UtlisNetWork.getnetwokstate(con);
            if (mode==0) {
                NetWork networ = new NetWork(handler);
                networ.getOpenKey(ieglog);
            } else if (mode==1){
                NetWork networ = new NetWork(handler);
                networ.getOpenKey(ieglog);

            }else if (mode==-1){
                return;
            }
        } catch (Exception e) {

        }
    }
public  void getkaimens(){

        try {
            ArrayList<MyOpenLog> listopen =  MySqliUtlis.getInstance(con).ShowddataOpenKey();
            if (listopen.size() == 0) {
                return;
            } else {
                IEGLogCtrl ieglog = new IEGLogCtrl();
                ieglog.EGLlist = new IEGLog[listopen.size()];
                for (int i = 0; i < listopen.size(); i++) {
                    ieglog.EGLlist[i] = new IEGLog();
                    ieglog.EGLlist[i].login_id = listopen.get(i).getLogin_id();
                    ieglog.EGLlist[i].eguard_id = listopen.get(i).getEguard_id();
                    ieglog.EGLlist[i].egkey_id = listopen.get(i).getEgkey_id();
                    ieglog.EGLlist[i].last_count = listopen.get(i).getLast_count();
                    ieglog.EGLlist[i].open_date = listopen.get(i).getOpen_date();
                    ieglog.EGLlist[i].create_date = listopen.get(i).getCreate_date();
                    ieglog.EGLlist[i].is_open = listopen.get(i).getIs_open();
                    ieglog.EGLlist[i].try_cnt = listopen.get(i).getTry_cnt();//重复开门次数
                    ieglog.EGLlist[i].phone_module = listopen.get(i).getPhone_module();
                    ieglog.EGLlist[i].open_type = listopen.get(i).getOpen_type();
                    ieglog.EGLlist[i].ord_date = listopen.get(i).getOrd_date();
                    ieglog.EGLlist[i].call_date = listopen.get(i).getCall_date();
                    ieglog.EGLlist[i].errinfo = listopen.get(i).getError();
                }
                int mode= UtlisNetWork.getnetwokstate(con);
                if (mode==0) {
                    NetWork networ = new NetWork(handler);
                    networ.getOpenKey(ieglog);
                } else if (mode==1){
                    NetWork networ = new NetWork(handler);
                    networ.getOpenKey(ieglog);

                }else if (mode==-1){
                    return;
                }
            }

        } catch (Exception e) {

        }


}
    class RefreshTask extends TimerTask {
        @Override
        public void run() {
            info = sharedPreferenceslog.getString("info", "");
            Log.e("main",info);
            texts.post(new Runnable() {
                @Override
                public void run() {
                    texts.setText(info);
                }
            });
        }
    }
    public  void hint(String name) {
        final DoubleButtonDialog dialog = new DoubleButtonDialog(
                con, name);
        dialog.getokbtn().setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                con.startActivity(new Intent(con,MyMabageDoor.class));
            }
        });
        dialog.getnobtn().setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

    }



}
